import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Calculator extends JFrame {
    // 成员变量
    private JPanel jPanel1;
    private JPanel jPanel2;
    private JTextField text1;
    private JTextField text2;

    public Calculator() {
        // 设置框架大小、位置、关闭方式、标题名称
        super("计算器");
        setSize(400, 400);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 初始化组件
        initComponents();
    }

    private void initComponents() {
        // 实例化面板和文本框
        jPanel1 = new JPanel(new BorderLayout());
        jPanel2 = new JPanel(new GridLayout(5, 4));

        // 设置文本框
        text1 = new JTextField();
        text2 = new JTextField();
        text1.setPreferredSize(new Dimension(20, 40));
        text1.setHorizontalAlignment(SwingConstants.RIGHT);
        text2.setPreferredSize(new Dimension(20, 40));
        text2.setHorizontalAlignment(SwingConstants.RIGHT);

        // 添加面板到框架
        add(jPanel1, BorderLayout.NORTH);
        add(jPanel2, BorderLayout.CENTER);

        // 添加按钮和事件监听器
        String[] buttons = {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+"};
        for (String buttonText : buttons) {
            JButton button = new JButton(buttonText);
            button.addActionListener(new ButtonClickListener(text1, text2));
            jPanel2.add(button);
        }

        // 设置可执行
        setVisible(true);
    }

    public static void main(String[] args) {
        new Calculator();
    }

    private class ButtonClickListener implements ActionListener {
        private JTextField text1;
        private JTextField text2;

        public ButtonClickListener(JTextField text1, JTextField text2) {
            this.text1 = text1;
            this.text2 = text2;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            JButton source = (JButton) e.getSource();
            String command = source.getActionCommand();

            if (command.charAt(0) == '=') {
                text1.setForeground(Color.RED);
            }

            // 其他按钮点击事件的处理逻辑
        }
    }
}